interface Option {
  startVal: number
  seconds: number
  timer: NodeJS.Timeout | undefined
  times: number
  defaultText: string
  countDownText: [string, string]
  againText: string
  starting: boolean
}

interface Option2 {
  startVal: number
  seconds: number
  timer?: NodeJS.Timer
  times?: number
  defaultText?: string
  countDownText?: [string, string]
  againText?: string
}

/**
 * 倒计时hook
 * @param option
 * @returns
 */
function useCountDown(option?: Option2) {
  const state = reactive<Option>({
    startVal: 0,
    seconds: 60,
    timer: undefined,
    times: 0,
    defaultText: '验证码',
    countDownText: ['', 's'],
    againText: '重新获取',
    starting: false
  })

  init(option)

  const isCountDownStart = computed(() => {
    return state.seconds >= (option ? option.startVal : 60)
  })

  const countDownText = computed(() => {
    if (!option) return state.defaultText

    if (state.seconds >= option.startVal) {
      if (state.times > 0) {
        return state.againText
      } else {
        return state.defaultText
      }
    } else {
      const [startStr, endStr] = state.countDownText
      return startStr + state.seconds + endStr
    }
  })

  function init(option?: Option2) {
    if (!option) return
    stopCountDown()
    const {defaultText, countDownText, againText, startVal, seconds} = option
    defaultText && (state.defaultText = defaultText)
    countDownText && (state.countDownText = countDownText)
    againText && (state.againText = againText)
    ;(startVal ?? null) !== null && (state.startVal = startVal)
    ;(seconds ?? null) !== null && (state.seconds = seconds)
  }

  function counDownStart() {
    state.starting = true
    stopCountDown()
    console.log('倒计时开始')
    state.timer = setInterval(() => {
      state.starting && (state.starting = false)
      state.seconds--
      console.log('倒计时递减中', state.seconds)
      if (state.seconds === 0) {
        stopCountDown()
        state.times++
      }
    }, 1000)
  }

  function stopCountDown() {
    if (!state.timer) return
    clearInterval(state.timer as unknown as number)
    state.seconds = option?.seconds || 60
    console.log('停止倒计时，重置倒计时状态', state.seconds, state.timer)
  }
  /**重置获取验证码的次数 */
  function resetTimes() {
    state.times = 0
  }
  onUnmounted(() => {
    resetTimes()
    stopCountDown()
  })
  return {
    resetTimes,
    stopCountDown,
    counDownStart,
    isCountDownStart,
    countDownText,
    starting: toRef(state, 'starting')
  }
}
export default useCountDown
